<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\utils\AppResult;
use app\utils\VueAdmin\Uploads;
use think\Db;
use think\exception\DbException;
use think\response\Json;

/**
 * vue 页面控制
 *
 * @icon fa fa-circle-o
 */
class Vue extends Backend
{
    protected $noNeedRight = '*';

    /**
     * 菜单操作按钮
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function operationPermissions()
    {
        // post请求获取数据
        $params = $this->request->param();
        $role = $this->auth->getRuleIds()[0] ?? '';
        $menu_rule  = $params['menu_rule'];
        $menu_id  = Db::name('auth_rule')->where('name', $menu_rule)->where('ismenu', 1)->value('id');
        $btn_list = Db::name('auth_rule')->where('pid', $menu_id)->where('ismenu', 0);
        if ($role != '*') {
            $role_menus_ids = explode(',',$role);
            $btn_list->whereIn('id', $role_menus_ids);
        }
        $btn_list = $btn_list->where('status', 'normal')->field(['id', 'title as name', 'name as path', 'name as action', 'icon'])->select();
        $btn      = [];
        foreach ($btn_list as $value) {
            $action = explode('/',$value['action']);
            $action = end($action);
            $btn[$action] = [
                'name'   => $value['name'],
                'path'   => $value['path'],
                'action' => $action,
                'icon'   => $value['icon'],
            ];
        }

        return AppResult::response200('success', $btn);
    }

    /**
     * 获取第三方云上传token
     * @return string
     */
    public function uploadToken()
    {
        $res = (Uploads::getInstance('image'))->token()->getMessage();
        if ($res['code'] != 200){
            return AppResult::response201($res['msg'], $res['data']);
        }
        return AppResult::response200('success', $res['data']);
    }

    public function gallery_iframe()
    {
        $params = $this->request->param();
        if ($this->request->isPost()) {
            $gallery = Db::name('attachment');
            if (!empty($params['keyword'])) {
                $gallery->where('filename', 'like', "%{$params['keyword']}%");
            }
            if (!empty($params['group_id'])) {
                $gallery->where('group_id', intval($params['group_id']));
            }
            if (!empty($params['type'])) {
                $imagetype = [
                    '1' => 'image',
                    '2' => 'video',
                ];
                $likeMimeType = $imagetype[$params['type']] ?? 'image';
                $gallery->where('mimetype', 'like', "%{$likeMimeType}%");
            }
            $res = $gallery->order('id', 'desc')->paginate($params['size'] ?? 12);

            return AppResult::response200('success', $res);
        } else {
            $ft = $params['ft'] ?? '1';
            $this->assign([
                'ft' => $ft,
                'mx' => $params['mx'] ?? '1',
                'dr' => $params['dr'] ?? '',
                'se' => $params['se'] ?? '10',
                'ck' => $params['ck'] ?? '',
                'sx' => $params['sx'] ?? (Uploads::$_fileTypeExt[$ft] ?? ''),
            ]);
            return $this->view->fetch('');
        }
    }

    public function gallery_group()
    {
        $type = \app\common\model\Attachment::getCategoryList();

        $list = [];
        foreach ($type as $k => $v) {
            $list[] = [
                'id' => $k, 'name' => $v, 'total' => 0, 'active' => false, 'remove' => false
            ];
        }
        return AppResult::response200('success', $list);
    }

    public function insert()
    {
        /*获取上传文件流*/
        if (!$file = $request->input('url')) {
            return AppResult::response201('文件保存失败！ERR:url');
        }
        if (!$key = $request->input('key')) {
            return AppResult::response201('文件保存失败！ERR:key');
        }
        if ((empty($request->driver) || ($request->driver != 'oss' && $request->driver != 'cos')) && !$disk = Uploads::disksQiNiu()) {
            return AppResult::response201('文件保存失败！ERR:driver');
        }

//        $size = $disk->size((string)($request->hash ?? ''));
        if ((empty($request->driver) || ($request->driver != 'oss' && $request->driver != 'cos'))) {
            $size = $disk->size((string)$key);
        }else{
            $size = $request->size ?? 0;
        }

        $file_name           = $request->input('file_name');
        $ext                 = explode('.', $file_name);
        $ext                 = end($ext);
        $gallery             = new AdminGalleryModel();
        $gallery->type       = $request->input('type');
        $gallery->group_id   = $request->input('group_id');
        $gallery->original   = $file_name ?: $key;
        $gallery->name       = (string)($request->hash ?? '');
        $gallery->url        = $file;
        $gallery->size       = (int) $size;
        $gallery->ext        = $ext;
        $gallery->status     = 1;
        $gallery->created_at = time();
        $gallery->save();
        return AppResult::response200('success！', $gallery->url);
    }

    public function gallery_upload()
    {
        /*获取上传文件流*/
        if (!$file = $request->file('file')) {
            return AppResult::response201('请上传文件！');
        }
        if (!$file->isValid()) {
            return AppResult::response201('文件上传失败！');
        }
        $size     = $request->size ? intval($request->input('size')) : 20;
        $type     = $request->type ? intval($request->input('type')) : 1;
        $group_id = $request->group_id ? intval($request->input('group_id')) : 1;
        $res      = (Uploads::getInstance('image', ['size' => $size, 'dir' => '', 'type' => $type]))->init('file')->getMessage();
        if ($res['code'] !== 200) {
            return AppResult::response201($res['msg']);
        }

        $gallery             = new AdminGalleryModel();
        $gallery->type       = $type;
        $gallery->group_id   = $group_id ? intval($group_id) : 1;
        $gallery->original   = $res['data']['file_name'];
        $gallery->name       = $res['data']['name'];
        $gallery->url        = $res['data']['url'];
        $gallery->size       = $res['data']['file_size'];
        $gallery->ext        = $res['data']['file_ext'];
        $gallery->status     = 1;
        $gallery->created_at = time();
        unset($file);
        $gallery->save();

        return AppResult::response200('success', $gallery->url);
    }

    public function remove()
    {
        if (empty($request->id) && empty($request->ids)) {
            return AppResult::response201('请选择需要操作的图片！');
        }
        if ($request->move == 'true') {
            $request->gid = $request->gid ? $request->gid : 0;
            if ($request->id) {
                AdminGalleryModel::query()->where('id', $request->id)->update(['gid' => $request->gid]);
            } else {
                $request->ids = DataUtil::stringToArray($request->ids);
                AdminGalleryModel::query()->whereIn('id', $request->ids)->update(['gid' => $request->gid]);
            }
        } else {
            if ($request->id) {
                AdminGalleryModel::query()->where('id', $request->id)->delete();
            } else {
                $request->ids = DataUtil::stringToArray($request->ids);
                AdminGalleryModel::query()->whereIn('id', $request->ids)->delete();
            }
        }
        return AppResult::response200('图片操作成功！');
    }

    public function original()
    {
        if(!$request->id)
        {
            return AppResult::response200('请选择需要操作的文件！');
        }
        if(!$request->name)
        {
            return AppResult::response200('请添加文件名！');
        }
        if(!AdminGalleryModel::query()->where('id', $request->id)->exists())
        {
            return AppResult::response200('文件不存在！');
        }
        AdminGalleryModel::query()->where('id', $request->id)->update([
            'original' => $request->name
        ]);
        return AppResult::response200('操作成功！');
    }
}
